package ma.zhiqiang.dataline.util;

import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.util.ReflectUtil;
import ma.zhiqiang.dataline.core.dto.Column;
import ma.zhiqiang.dataline.core.handler.FieldHandler;

import java.util.concurrent.ConcurrentHashMap;

public class HandlerUtil {
    static ConcurrentHashMap<String,Object> concurrentHashMap = new ConcurrentHashMap<>();
    public static Column columnFieldHandle(String fieldHandlerClass, Column column){
        FieldHandler fieldHandler = null;
        Object object = concurrentHashMap.get(fieldHandlerClass);
        if(object!=null){
            fieldHandler = (FieldHandler) object;
        }else{
            try {
                fieldHandler = ReflectUtil.newInstance(fieldHandlerClass);
                concurrentHashMap.put(fieldHandlerClass,fieldHandler);
            } catch (UtilException e) {
                throw new RuntimeException(e);
            }
        }
        return fieldHandler.handle(column);
    }
    public static String stringFieldHandle(String fieldHandlerClass, String value){
        FieldHandler fieldHandler = null;
        Object object = concurrentHashMap.get(fieldHandlerClass);
        if(object!=null){
            fieldHandler = (FieldHandler) object;
        }else{
            try {
                fieldHandler = ReflectUtil.newInstance(fieldHandlerClass);
                concurrentHashMap.put(fieldHandlerClass,fieldHandler);
            } catch (UtilException e) {
                throw new RuntimeException(e);
            }
        }
        return fieldHandler.handle(value);
    }
}
